package Java7_Concurrency_Cookbook.concurrent_custom.custom_thread_pool_executor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * <b>定制ThreadPoolExecutor</b><br/>
 * <br/>
 * 本示例中, 线程执行前, 后, 以及执行器关闭都会有响应的控制台输出<br/>
 * executor.shutdown()后, 正在休眠的线程会被中断<br/>
 * 执行结果会看起来比较凌乱, 因为Main线程和执行任务的线程不具有偏序关系<br/>
 * @author lixiangke
 * @date 2017/11/24
 */
public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyExecutor executor = new MyExecutor(2, 4,
                1000, TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<Runnable>());
        List<Future<String>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            SleepTwoSecondsTask task = new SleepTwoSecondsTask();
            Future<String> result = executor.submit(task);
            results.add(result);
        }

        for (int i = 0; i < 5; i++) {
            String result = results.get(i).get();
            System.out.printf("Main: Results for task %d : %s. \n", i, result);
        }

        executor.shutdown();

        for (int i = 5; i < 10; i++) {
            String result = results.get(i).get();
            System.out.printf("Main: Results for task %d : %s. \n", i, result);
        }

        executor.awaitTermination(1, TimeUnit.DAYS);
        System.out.println("End of the program.");
    }
}
